//
//  LHServerManager.m
//  LazyHome
//
//  Created by yh on 2018/5/14.
//  Copyright © 2018年 yh. All rights reserved.
//

#import "LHServerManager.h"
#import <MJExtension/MJExtension.h>
#define LHServerManagerArchiverPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"LHServerManager.data"]
@implementation LHServerManager
MJCodingImplementation
+ (instancetype)manager{
    static dispatch_once_t onceToken;
    static LHServerManager *shareInstatnce = nil;
    dispatch_once(&onceToken, ^{
       shareInstatnce = [NSKeyedUnarchiver unarchiveObjectWithFile:LHServerManagerArchiverPath];
        if (!shareInstatnce) {
            shareInstatnce = [[LHServerManager alloc] init];
            shareInstatnce.currentServerModel = [[ServerModel alloc] init];
            shareInstatnce.servers = [[NSMutableArray alloc] init];
            [shareInstatnce.servers addObject:shareInstatnce.currentServerModel];
            [NSKeyedArchiver archiveRootObject:shareInstatnce toFile:LHServerManagerArchiverPath];
        }
      
        
        
    
    });
    return shareInstatnce;
}

- (void)changeCurrentServerModelTo:(ServerModel *)model{
    self.currentServerModel = model;
    [self save];
}

- (void)addServer:(ServerModel *)serverModel{
    [self.servers addObject:serverModel];
    [self save];
}

- (void)removeServer:(ServerModel *)serverModel{
    if ([self.servers containsObject:serverModel]) {
        [self.servers removeObject:serverModel];
    }else{
        for (ServerModel *item  in self.servers) {
            if ([item.serverId isEqualToString:serverModel.serverId]) {
                [self.servers removeObject:serverModel];
                break;
            }
        }
    }
    [self save];
}

- (void)modifyServer:(ServerModel *)serverModel{
    if ([self.servers containsObject:serverModel]) {
        [self.servers replaceObjectAtIndex:[self.servers indexOfObject:serverModel] withObject:serverModel];
    }else{
        for (ServerModel *item  in self.servers) {
            if ([item.serverId isEqualToString:serverModel.serverId]) {
                [self.servers replaceObjectAtIndex:[self.servers indexOfObject:item] withObject:serverModel];
                break;
            }
        }
    }
    [self save];
    
}

- (void)save{
    [NSKeyedArchiver archiveRootObject:self toFile:LHServerManagerArchiverPath];
}

@end
